<template>
  <div class="search-bar" style="width: 1200px">
    <div class="search-bar-container">
      <el-autocomplete
          class="search-input custom-search-input"
          v-model="searchQuery"
          :fetch-suggestions="querySearch"
          placeholder="搜索..."
          @select="handleSelect"
          @query-change="resetSuggestions"
          style="height: 40px;"
      >
        <template slot="append">
            <el-button icon="el-icon-search" @click="search">搜索</el-button>
        </template>
      </el-autocomplete>
    </div>
    <ul v-show="showSuggestions" class="suggestion-list">
      <li v-for="item in suggestions" :key="item.id" @click="handleSelect(item)">{{ item.name }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchQuery: "",
      suggestions: [],
      items: [
        { id: 1, value: "苹果" },
        { id: 2, value: "香蕉" },
        { id: 3, value: "橙子" },
        { id: 4, value: "芒果" },
        { id: 5, value: "草莓" }
      ],
      showSuggestions: false
    };
  },
  computed: {
    filteredItems() {
      if (this.searchQuery) {
        console.log(this.searchQuery)
        return this.items.filter(item =>
            item.value.toLowerCase().includes(this.searchQuery.toLowerCase())
        );
      } else {
        return this.items;
      }
    }
  },
  methods: {
    querySearch(queryString, cb) {
      if (queryString) {
        console.log(queryString)
        const results = this.items.filter(item =>
            item.value.toLowerCase().includes(queryString.toLowerCase())
        );
        console.log(results)
        cb(results);
      } else {
        cb([]);
      }
    },
    resetSuggestions() {
      if (this.searchQuery) {
        this.showSuggestions = true;
      } else {
        this.showSuggestions = false;
      }
    },
    handleSelect(item) {
      this.searchQuery = item.value;
      this.showSuggestions = false;
    },
    search() {
      // 处理搜索逻辑
      console.log(this.searchQuery)
    }
  }
};
</script>

<style scoped>
.search-bar {
  margin: 0 auto;
  padding: 20px;
}
.search-bar-container {
  display: flex;
  justify-content: center;
}

::v-deep .el-input__inner {
  height: 60px; /* 设置所需的高度 */
}

.search-input {
  width: 80%;
}

ul {
  margin-top: 20px;
  padding: 0;
  list-style: none;
}

li {
  padding: 5px;
  border-bottom: 1px solid #ddd;
  cursor: pointer;
}

li:hover {
  background-color: #f5f5f5;
}

.el-autocomplete .el-input {
  border-radius: 20px;
}

.el-button--primary {
  border-radius: 20px;
}

.suggestion-list {
  position: fixed;
  z-index: 9999;
  width: 1200px;
  background-color: #fff;
  padding: 10px;
  max-height: 200px;
  overflow-y: auto;
  box-shadow: 0px 2px 6px rgba(0, 0, 0, 0.1);
}
</style>
